package com.bjpowernode.rbac.web.interceptor;

import com.bjpowernode.rbac.anno.RequestPermission;
import com.bjpowernode.rbac.entity.Employee;
import com.bjpowernode.rbac.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Employee employee = UserContext.getEmployee();
        if (employee.isAdmin()) {
            // 超管
            return true;
        }
        List<String> permission = UserContext.getPermission();

        if (handler instanceof HandlerMethod) {
            RequestPermission requestPermission = ((HandlerMethod) handler).getMethodAnnotation(RequestPermission.class);
            if (requestPermission == null) {
                // 方法不需要权限
                return true;
            }
            String expression =  requestPermission.value()[1];
            if (permission.contains(expression)) {
                // 有权限
                return true;
            }

        }
        response.sendRedirect("/anno/nopermission");
        return false;
    }
}
